﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;

using AutoMapper;

using KSOAdmin.Core.CacheHelper.Interface;
using KSOAdmin.Core.EFDbContext;
using KSOAdmin.Core.MD5Helper;
using KSOAdmin.IRepository;
using KSOAdmin.IRepository.System;
using KSOAdmin.IServices.System;
using KSOAdmin.Models.Core;
using KSOAdmin.Models.DomainModels.System;
using KSOAdmin.Models.ViewModel;

namespace KSOAdmin.Services.System
{
    public class SysUserServices : BasicServices<Sys_User>, ISys_UserServices, IDependency
    {
        private readonly ICacheService _RedisService;
        private readonly IMapper _iMapper;
        private readonly ISys_UserRepository _pository;
        private readonly IBasicRepository<Sys_User> _BaseRepository;
        public SysUserServices(ISys_UserRepository pository, IBasicRepository<Sys_User> BaseRepository, IMapper iMapper, ICacheService RedisService)
        {
            this._iMapper = iMapper;
            this._pository = pository;
            this.repository = BaseRepository;//父类
            this._BaseRepository = BaseRepository;
            this._RedisService = RedisService;
        }
        /// <summary>
        /// 登录的查询
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<(ResponseModel, View_Sys_User)> LoginVerificationAsync(View_Sys_User user)
        {
            ResponseModel response = new() { code = 500 };
            if (string.IsNullOrWhiteSpace( user.UserPwd) )
            {
                response.msg = "密码输入格式不正确";
                return (response, user);
            }
            if (user.UserName?.Trim().Length < 3)
            {
                response.msg = "用户名输入格式不正确";
                return (response, user);
            }
            if (user.UserName!= "KSO") //免检产品
            {
                if (user.UserVerification?.Trim().Length != 4)
                {
                    response.msg = "验证码输入格式不正确";
                    return (response, user);
                }
                else
                {
                    string code = _RedisService.Get(user.UUID,Core.CacheHelper.CacheDataType.VerificationCode);
                    if (code is null || code.ToLower() != user.UserVerification.ToLower())
                    {
                        response.msg = "验证码输入错误";
                        return (response, user);
                    }
                }
            }
           
            user.UserPwd = MD5.GetMD5Hash(user.UserPwd);
            Sys_User sys_User = await _pository.FindFirstAsync(w => (w.UserName == user.UserName || w.Email == user.UserName || w.PhoneNo == user.UserName) && w.UserPwd == user.UserPwd && w.Enable == 1);
            if (sys_User is null)
            {
                response.code = 401;
                response.msg = "找不到此用户，请先注册";
                return (response, user);
            }
            else
            {
                response.code = 200;
                response.msg = "执行成功";
            }
            return (response, _iMapper.Map<Sys_User, View_Sys_User>(sys_User));
        }
 
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel> CreateRegister([NotNull]View_Sys_User view_Sys)
        {
            if (string.IsNullOrWhiteSpace(view_Sys?.UserName))
            {
                return ResponseModel.Fail("用户名不能为空");
            }
            if (string.IsNullOrWhiteSpace(view_Sys?.Email))
            {
                return ResponseModel.Fail("邮箱不能为空");
            }
            if (string.IsNullOrWhiteSpace(view_Sys?.PhoneNo))
            {
                return ResponseModel.Fail("手机号不能为空");
            }
            var sysuer= await _pository.FindFirstAsync(w=>w.UserName==view_Sys.UserName || w.Email==view_Sys.Email || w.PhoneNo==view_Sys.PhoneNo);

            if (sysuer!=null) return ResponseModel.Fail("此用户名或手机或邮箱，已存在",500);

            if (view_Sys.UserPwd2!=view_Sys.UserPwd || string.IsNullOrWhiteSpace(view_Sys.UserPwd))
            {
                return ResponseModel.Fail("两次密码输入不相同",500);
            }
            Sys_User sysu= _iMapper.Map<View_Sys_User,Sys_User>(view_Sys);
            sysu.AuditDate = DateTime.UtcNow;
            sysu.AuditStatus = 1;
            sysu.CreateDate=DateTime.UtcNow;
            sysu.CreateID=1;
            sysu.Enable = 1;
            sysu.Dept_Id = 1;
            sysu.DeptName = "新用户";
            sysu.RoleName = "新用户角色";
            sysu.UserTrueName = view_Sys.UserName;
            int row=  await _pository.AddAsync(sysu);
            return ResponseModel.Success("创建成功");
        }



    }
}
